#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

/*

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);


int pthread_join(pthread_t thread, void **retval);
void pthread_exit(void *retval);

// pthread_attr_t attr;
// int pthread_attr_init(pthread_attr_t *attr);
// int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
// int pthread_attr_destroy(pthread_attr_t *attr);


// int pthread_detach(pthread_t thread);

// pthread_t pthread_self(void);

int pthread_cancel(pthread_t thread);
int pthread_setcancelstate(int state, int *oldstate);
*/

int pthread_status = 11;

void *start_routine(void *arg)
{
    // 设置子线程不响应取消请求
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
    int count = 0;

    printf("子线程 %d\n", *((int *)arg));
    while (count < 20)
    {
        printf("world\n");
        sleep(1);
        count++;
    }
    // 设置子线程响应取消请求
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    while (1)
    {
        printf("new world\n");
        sleep(1);
    }
}

int main()
{
    int count = 1;

    printf("main 单个进程 的主线程\n");

    // 创建一个线程
    pthread_t thread;
    int res = pthread_create(&thread, NULL, start_routine, &count);
    printf("res=%d\n", res);

    while (count < 10)
    {
        printf("hello\n");
        sleep(1);
        count++;
    }

    printf("退出循环 发送取消线程请求\n");
    pthread_cancel(thread);   
    printf("================\n");
    pause();

    return 0;
}
